﻿using System;
using System.Web.Script.Serialization;
using System.Collections.Generic;
using System.Configuration;
using System.Web.Mvc;
using System.Net;
using System.Text;
using XZL.Web.Biz;
using XZL.Web.Da;
using XZL.Web.Entity;


namespace XZL.Web.MVC.Controllers
{
    public class UserController : Controller
    {
        string appid = ConfigurationManager.AppSettings["appid"];
        string appsecret = ConfigurationManager.AppSettings["appsecret"];
        string redirecturi= ConfigurationManager.AppSettings["redirecturi"];
        string templateID = "s1ynQ1wnQeC4FTtnUlPyaFhQ3mHcnBVsctwL95a5MaQ"; //注册成功模版消息

        /// <summary>
        ///  注册
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Register(string id)
        {
            string code = Request.QueryString["code"];
            string state = Request.QueryString["state"];

            if (code != null)
            {
                //获取access_token && openID
                string send_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + appsecret + "&code=" + code + "&grant_type=authorization_code";
                var client = new System.Net.WebClient();
                client.Encoding = System.Text.Encoding.UTF8;
                var data = client.DownloadString(send_url);
                var serializer = new JavaScriptSerializer();
                var obj = serializer.Deserialize<Dictionary<string, string>>(data);
                string accessToken;
                if (!obj.TryGetValue("access_token", out accessToken))
                {
                    return RedirectToAction("NoInviter", "User", new { Error = "Code" });
                }
                HttpContext.Session["Token"] = accessToken;
                var opentid = obj["openid"];
                if (opentid == null || opentid == "")
                {
                    return RedirectToAction("NoInviter", "User", new { Error = "Code" });
                }
                ViewBag.OpenID = opentid;

                //获取用户信息
                var url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", accessToken, opentid);
                data = client.DownloadString(url);
                var user = serializer.Deserialize<Dictionary<string, object>>(data);
                var img = user["headimgurl"].ToString();
                var nick = user["nickname"].ToString();
                var sex = user["sex"].ToString();
                if (sex == "1")
                {
                    ViewBag.Sex = "男";
                }
                else if (sex == "2")
                {
                    ViewBag.Sex = "女";
                }
                else
                {
                    ViewBag.Sex = "未知";
                }

                ViewBag.Image = img;
                ViewBag.NickName = nick;
                ViewBag.Code = code;
                ViewBag.State = state;

                //微信登录
                UserInfo myInfo = UserBiz.LoginByWeiXin(opentid,nick,img);
                if (myInfo != null)
                {
                    //帐号被禁用
                    if (myInfo.Status == -1)
                    {
                        return RedirectToAction("NoInviter", "User", new { Error = "Disable" });
                    }
                    //登录成功
                    HttpContext.Session["MyInfo"] = myInfo;
                    //return RedirectToAction("Index", "Home");
                    string page = "";
                    if (state.Contains("CourseInfo"))
                    {
                        page = state + "&InviteID=" + myInfo.UserNum;
                    }
                    else
                    {
                        page = state;
                    }
                    return Redirect(page);
                }            
            }
            else
            {
                return RedirectToAction("NoInviter", "User", new { Error = "Code" });
            }

            //获取邀请人信息
            try
            {
                Proc_UserInfo_SelectByUserNumResult user = UserBiz.GetUserInfoByUserNum(Convert.ToInt32(id));
                if (user != null)
                {
                    ViewBag.InviterID = user.UserID;
                    string img = user.HeadPortrait;
                    if (img == "" || img == null)
                    {
                        img = "../Image/defaultHead2.jpg";
                    }
                    ViewBag.InviterImg = img;
                    ViewBag.InviterName = user.NickName;
                    ViewBag.InviterPhone = user.MobilePhone;
                }
                //无邀请人
                else
                {
                    return RedirectToAction("NoInviter", "User", new { Error = "Inviter" });
                }
            }
            catch
            {
                return RedirectToAction("NoInviter", "User", new { Error = "Inviter" });
            }
            return View();
        }

        /// <summary>
        /// 注册页面[提交表单]
        /// </summary>
        /// <param name="fc"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Register(FormCollection fc)
        {
            string uID = Guid.NewGuid().ToString();
            string inviterID = fc["InviterID"];
            ViewBag.InviterID = inviterID;
            string phone = fc["Phone"];
            phone = phone.Replace(" ", "");
            string inviterPhone = fc["InviterPhone"];
            ViewBag.InviterPhone = inviterPhone;
            string inviterName = fc["InviterName"];
            ViewBag.InviterName = inviterName;
            string inviterImg = fc["InviterImg"];
            ViewBag.InviterImg = inviterImg;
            string code = fc["MobileCode"];
            string pwdStr = fc["Pwd"];
            //Random rad = new Random();
            //string pwdStr = rad.Next(100001, 1000000).ToString();
            //string pwd = CommonMethods.StrToMD5(pwdStr);
            string pwd = CommonMethods.StrToMD5(pwdStr);

            string weixinCode = fc["Code"];
            ViewBag.Code = weixinCode;
            string state = fc["State"];
            ViewBag.State = state;
            string token = fc["Token"];
            ViewBag.Token = token;
            string sex = fc["Sex"];
            ViewBag.Sex = sex;
            string weixinID = fc["OpenID"];
            ViewBag.OpenID = weixinID;
            string weixinName = fc["NickName"];
            ViewBag.NickName = weixinName;
            string headImg = fc["Image"];
            ViewBag.Image = headImg;
            ViewBag.Phone = phone;

            //验证手机号
            if (phone.Length != 11)
            {
                ViewBag.ErrorInfo = "手机号输入错误！";
                return View();
            }

            //验证 验证码
            string msg = UserBiz.GetMobileCode(phone);
            if (code != msg)
            {
                ViewBag.ErrorInfo = "验证码错误！";
                return View();
            }

            //注册结果
            int i = UserBiz.Register(uID, inviterID, weixinID, weixinName, weixinName, headImg, pwd, phone);

            //成功
            if (i == 0)
            {
                //短信通知
                string strUser = "感谢您成为我们尊贵的会员。您的注册帐号为：" + phone + "，如有任何问题，请联系客服：010-64756681 / 64758501。";
                string strInviter = "尊敬的会员：" + inviterName + "，恭喜您成功推荐一位新会员注册。帐号：" + phone;
                int res1 = UserBiz.SendMobileCode(phone, strUser);
                int res2 = UserBiz.SendMobileCode(inviterPhone, strInviter);

                token = Get_Access_token();
                //微信通知
                var data = WXTemplate.RegisterSuccessful("感谢您成为我们尊贵的会员", weixinName, phone, "如有任何问题，请联系客服：010-64756681 / 64758501。");
                SendTemplateMessageService.SendTemplateMessage(templateID, weixinID, "wfdot.com/myinfo/index", token, data);
                
                //跳转页面
                return RedirectToAction("RegisterSuccessful", "User");
            }
            else if (i == -1)
            {
                ViewBag.ErrorInfo = "手机号已注册，请重新输入！";
            }
            else if (i == -2)
            {
                ViewBag.ErrorInfo = "微信号已注册，请点击登录！";

            }

            return View();
        }

        /// <summary>
        /// 注册失败
        /// </summary>
        /// <returns></returns>
        public ActionResult NoInviter()
        {
            string error = Request.QueryString["Error"];
            if (error == "Code")
            {
                ViewBag.ErrorTitle = "登录失败！";
                ViewBag.ErrorInfo = "请使用微信打开本链接！";
            }
            else if (error == "Inviter")
            {
                ViewBag.ErrorTitle = "抱歉，您不是网非会员！";
                ViewBag.ErrorInfo = "会员必须通过邀请才能注册加盟，如需帮助请联系客服电话：010-64756681/64758501";
            }
            else if (error == "Disable")
            {
                ViewBag.ErrorTitle = "抱歉，登录失败！";
                ViewBag.ErrorInfo = "您的帐号已被管理员禁用，如需帮助请联系客服电话：010-64756681/64758501";
            }
            return View();
        }

        /// <summary>
        /// 注册成功
        /// </summary>
        /// <returns></returns>
        public ActionResult RegisterSuccessful(string id)
        {
            ViewBag.Phone = id;
            string link1 = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+redirecturi;
            string link2 = "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
            ViewBag.Link = link1 + "10001" + link2;
            return View();
        }

        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult SendValiCode(string phone)
        {
            Random rad = new Random();
            int mobile_code = rad.Next(100000, 1000000);
            string msg = "您的验证码是：" + mobile_code + "。请不要把验证码泄露给其他人。";
            int res = UserBiz.SendMobileCode(phone, msg);
            if (res == 1)
            {
                UserBiz.UpdateMobileCode(phone, mobile_code.ToString());
                return Json("1");
            }
            else
            {

            }
            return Json("-1");
        }

        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public JsonResult GetValiCode(string phone)
        {
            string code = UserBiz.GetMobileCode(phone);
            return Json(code);
        }

        /// <summary>
        /// 登录页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Login()
        {
            return View();
        }

        /// <summary>
        /// 登录页面 [提交表单]
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Login(FormCollection fc)
        {
            //登录方式
            string loginType = fc["LoginType"];

            //普通登录
            if (loginType == "Account")
            {
                string uName = fc["UserName"];
                uName = uName.Replace(" ", "");
                string pwd = fc["Pwd"];

                if (uName.Length > 14 || uName.Length < 6)
                {
                    ViewBag.ErrorAccount = "请输入6-14位账户名！";
                    return View();
                }

                pwd = CommonMethods.StrToMD5(pwd);
                UserInfo user = UserBiz.LoginByPhone(uName, pwd);
                if (user != null)
                {
                    HttpContext.Session["MyInfo"] = user;
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ViewBag.ErrorAccount = "帐号或密码错误，请重新输入！";
                    ViewBag.Page = "Account";
                    return View();
                }
            }

            //验证码登录
            else if (loginType == "Phone")
            {
                string phone = fc["Phone"];
                phone = phone.Replace(" ", "");
                string code = fc["MobileCode"];

                if (phone.Length != 11)
                {
                    ViewBag.ErrorPhone = "请输入正确的手机号！";
                    return View();
                }

                UserInfo user = UserBiz.LoginByCode(phone, code);

                if (user != null)
                {
                    HttpContext.Session["MyInfo"] = user;
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ViewBag.ErrorPhone = "手机号或验证码错误，请重新输入！";
                    ViewBag.Page = "Phone";
                    return View();
                }

            }
            return View();
        }


        /// <summary>
        /// 获得access_token
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="appsecret"></param>
        /// <returns></returns>
        public string Get_Access_token()
        {
            WebClient webclient = new WebClient();
            string url = @"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret + "";
            byte[] bytes = webclient.DownloadData(url);//在指定的path上下载
            string result = Encoding.GetEncoding("utf-8").GetString(bytes);//转string
            JavaScriptSerializer js = new JavaScriptSerializer();
            AccessToken amodel = js.Deserialize<AccessToken>(result);//此处为定义的类，用以将json转成model
            string a_token = amodel.access_token;
            return a_token;
        }
    }
}